﻿/************************************************
* Copyright (C) 2011 东北农业大学(NEAU) 版权所有。
* 文件名：
* 版本号：
* 文件功能描述：文件柜
* 作者：于静
* 创建日期:2011-04-03
* 版本号：
* 修改人：
* 修改日期：
* 修改描述：
************************************************/
Ext.BLANK_IMAGE_URL = '/script/ext/resources/images/s.gif';
Ext.onReady(function () {
    var modelid = jQuery.query.get("modelid");
    //初始化快速提示
    Ext.QuickTips.init();
    //将提示显示在form属性旁边
    Ext.form.Field.prototype.msgTarget = "side";
    //创建根节点
    var DepmetTreeRoot = new Ext.tree.AsyncTreeNode({ text: '文件柜树', id: 'DepmetTreeRoot', expanded: true, leaf: false });
    //创建树面板
    var DepmetTree = new Ext.tree.TreePanel({
        loader: new Ext.tree.TreeLoader({ dataUrl: "SERVER/files/FoldersTree.aspx?r=" + new Date().getTime() }),
        id: 'DepmetTree',
        region: 'west',
        width: 140,
        minSize: 140,
        margins: '5 0 5 5',
        cmargins: '5',
        bodyStyle: "padding:5px;",
        title: "文件夹",
        split: true,
        rootVisible: false,
        lines: true,
        autoScroll: true,
        animate: true,
        collapsible: true,
        containerScroll: true,
        tbar: [{ iconCls: 'icon-expand-all',
            tooltip: '全部展开',
            handler: function () { DepmetTreeRoot.expand(true); }
        }, { iconCls: 'icon-collapse-all',
            tooltip: '全部折叠',
            handler: function () { DepmetTreeRoot.collapse(true); }
        }, { iconCls: 'icon-add',
            tooltip: '添加同级',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                DepmetAdd(DepmetTree, DepmetTreeRoot, selectNode, true);
            }
        }, { iconCls: 'icon-add',
            tooltip: '添加子集',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                DepmetAdd(DepmetTree, DepmetTreeRoot, selectNode, false);
            }
        }, { iconCls: 'icon-edit',
            tooltip: '编辑',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                if (selectNode) {
                    Ext.Msg.prompt("文件夹", "请输入文件夹名称", function (btn, text) {
                        if (btn == "ok") {
                            if (text != "") {
                                Ext.Ajax.request({
                                    url: "SERVER/files/FoldersAdd.aspx?modelid=" + modelid,
                                    method: 'POST',
                                    params: { text: text, nodeId: selectNode.id },
                                    success: function (response) {
                                        var json = Ext.util.JSON.decode(response.responseText);
                                        if (json.success) {
                                            Ext.Msg.alert("提示", json.msg);
                                            DepmetTree.loader.load(DepmetTreeRoot);
                                        } else {
                                            Ext.Msg.alert("错误", json.msg);
                                        }
                                    }
                                });
                            } else {
                                Ext.Msg.alert("提示", "请输入名称");
                            }
                        }
                    }, "", "", selectNode.text);
                }
            }
        }, { iconCls: 'icon-del',
            tooltip: '删除',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                if (selectNode) {
                    Ext.Msg.confirm("确认提示", "确认要删除" + selectNode.text + "?", function (btn) {
                        if (btn == "yes") {
                            Ext.Ajax.request({
                                url: "SERVER/files/FoldersDel.aspx?modelid=" + modelid,
                                method: 'POST',
                                params: { nodeId: selectNode.id },
                                success: function (response) {
                                    var json = Ext.util.JSON.decode(response.responseText);
                                    if (json.success) {
                                        Ext.Msg.alert("提示", json.msg);
                                        DepmetTree.loader.load(DepmetTreeRoot);
                                    } else {
                                        Ext.Msg.alert("错误", json.msg);
                                    }
                                }
                            });
                        }
                    }, "", "", selectNode.text);
                }
            }
        }]
    });
    DepmetTree.setRootNode(DepmetTreeRoot);
    DepmetTree.on('dblclick', function (node, e) {
        e.stopEvent();
        var model = DepmetTree.getSelectionModel();
        var selectNode = model.getSelectedNode();
        if (selectNode) {
            groupStore.load({ params: { start: 0, limit: pageSize, depmetId: selectNode.id} });
        }
    });
    DepmetTree.on('checkchange', function (node, checked) {
        selectParentNode(node, checked);
        selectChildNode(node, checked);
    }, DepmetTree);
    //定义请求参数
    var proxy = new Ext.data.HttpProxy({ url: "SERVER/files/FilesList.aspx?r=" + new Date().getTime() });
    //定义数据模型
    var UserInfo = new Ext.data.Record.create([
                        { name: 'ID', type: 'int', mappging: "ID" },
                        { name: 'Name', type: 'string', mappging: "Name" },
                        { name: 'Type', type: 'string', mappging: "Type" },
                        { name: 'Size', type: 'string', mappging: "Size" },
                        { name: 'CreateID', mappging: "CreateID" },
                        { name: 'ParentID', mappging: "ParentID" },
                        { name: 'CreateTime', mappging: "CreateTime" },
                        { name: 'PathNow', mappging: "PathNow" },
                        { name: 'IsPw', mappging: "IsPw" },
                        { name: 'PW', mappging: "PW" }
                        ]);
    //创建阅读器
    var reader = new Ext.data.JsonReader({ totalProperty: "Count", root: "List" }, UserInfo);
    var formReader = new Ext.data.JsonReader({}, UserInfo);
    //创建数据源
    var groupStore = new Ext.data.GroupingStore({
        proxy: proxy,
        reader: reader,
        sortInfo: { field: 'ID', direction: 'DESC' }
    });
    //设置每页条数
    var pageSize = 20;
    var cookiePageSize = parseInt(Ext.util.Cookies.get("pageSize"));
    if (cookiePageSize) { pageSize = cookiePageSize; }
    //加载数据源
    groupStore.load({ params: { start: 0, limit: pageSize} });
    //创建选择列模型
    var sm = new Ext.grid.CheckboxSelectionModel();
    //定义列模型
    var cm = new Ext.grid.ColumnModel([
            new Ext.grid.RowNumberer(),
            sm,
            { id: 'id', header: '编号', dataIndex: 'ID', width: 60, sortable: true },
            { id: 'name', header: '文件名', dataIndex: 'Name', width: 150, sortable: true, align: "center" },
            { id: 'type', header: '文件类型', dataIndex: 'Type', width: 60, sortable: true, align: "center",
                renderer: function (v) {
                    if (v == "bmp") {
                        return "<img src='resources/images/FileType/bmp.gif'>";
                    }
                    if (v == "chm") {
                        return "<img src='resources/images/FileType/chm.gif'>";
                    }
                    if (v == "csv") {
                        return "<img src='resources/images/FileType/csv.gif'>";
                    }
                    if (v == "dll") {
                        return "<img src='resources/images/FileType/dll.gif'>";
                    }
                    if (v == "eml") {
                        return "<img src='resources/images/FileType/eml.gif'>";
                    }
                    if (v == "exe") {
                        return "<img src='resources/images/FileType/exe.gif'>";
                    }
                    if (v == "ttf") {
                        return "<img src='resources/images/FileType/font.gif'>";
                    }
                    if (v == "gif") {
                        return "<img src='resources/images/FileType/gif.gif'>";
                    }
                    if (v == "hlp") {
                        return "<img src='resources/images/FileType/hlp.gif'>";
                    }
                    if (v == "html") {
                        return "<img src='resources/images/FileType/ie.gif'>";
                    }
                    if (v == "ini") {
                        return "<img src='resources/images/FileType/ini.gif'>";
                    }
                    if (v == "java") {
                        return "<img src='resources/images/FileType/java.gif'>";
                    }
                    if (v == "jpg") {
                        return "<img src='resources/images/FileType/jpeg.gif'>";
                    }
                    if (v == "jpeg") {
                        return "<img src='resources/images/FileType/jpeg.gif'>";
                    }
                    if (v == "mdb") {
                        return "<img src='resources/images/FileType/mdb.gif'>";
                    }
                    if (v == "mp3") {
                        return "<img src='resources/images/FileType/media.gif'>";
                    }
                    if (v == "rmvb") {
                        return "<img src='resources/images/FileType/media.gif'>";
                    }
                    if (v == "mp4") {
                        return "<img src='resources/images/FileType/media.gif'>";
                    }
                    if (v == "mpeg") {
                        return "<img src='resources/images/FileType/media.gif'>";
                    }
                    if (v == "rm") {
                        return "<img src='resources/images/FileType/media.gif'>";
                    }
                    if (v == "xls") {
                        return "<img src='resources/images/FileType/msexcel.gif'>";
                    }
                    if (v == "xlsx") {
                        return "<img src='resources/images/FileType/msexcel.gif'>";
                    }
                    if (v == "ppt") {
                        return "<img src='resources/images/FileType/msppt.gif'>";
                    }
                    if (v == "pptx") {
                        return "<img src='resources/images/FileType/msppt.gif'>";
                    }
                    if (v == "doc") {
                        return "<img src='resources/images/FileType/msword.gif'>";
                    }
                    if (v == "docx") {
                        return "<img src='resources/images/FileType/msword.gif'>";
                    }
                    if (v == "pdf") {
                        return "<img src='resources/images/FileType/pdf.gif'>";
                    }
                    if (v == "pps") {
                        return "<img src='resources/images/FileType/pps.gif'>";
                    }
                    if (v == "psd") {
                        return "<img src='resources/images/FileType/psd.gif'>";
                    }
                    if (v == "rar") {
                        return "<img src='resources/images/FileType/rar.gif'>";
                    }
                    if (v == "rtf") {
                        return "<img src='resources/images/FileType/rtf.gif'>";
                    }
                    if (v == "shareFolder") {
                        return "<img src='resources/images/FileType/shareFolder.gif'>";
                    }
                    if (v == "sql") {
                        return "<img src='resources/images/FileType/sql.gif'>";
                    }
                    if (v == "swf") {
                        return "<img src='resources/images/FileType/swf.gif'>";
                    }
                    if (v == "sys") {
                        return "<img src='resources/images/FileType/sys.gif'>";
                    }
                    if (v == "txt") {
                        return "<img src='resources/images/FileType/txt.gif'>";
                    }
                    if (v == "vsd") {
                        return "<img src='resources/images/FileType/vsd.gif'>";
                    }
                    if (v == "wab") {
                        return "<img src='resources/images/FileType/wab.gif'>";
                    }
                    if (v == "wps") {
                        return "<img src='resources/images/FileType/wpsdoc.gif'>";
                    }
                    if (v == "xml") {
                        return "<img src='resources/images/FileType/xml.gif'>";
                    }
                    else {
                        return "<img src='resources/images/FileType/default.gif'>";
                    }
                }
            },
            { id: 'size', header: '文件大小', dataIndex: 'Size', width: 80, sortable: true, align: "center" },
            { id: 'parentid', header: '文件夹', dataIndex: 'ParentID', width: 100, sortable: true, renderer: rendererDepmet(), align: "center" },
            { id: 'createid', header: '发布人', dataIndex: 'CreateID', width: 80, sortable: true, align: "center" },
            { id: 'createtime', header: '发布时间', dataIndex: 'CreateTime', width: 120, sortable: true, renderer: Ext.util.Format.dateRenderer('Y-m-d'), format: "Y-m-d", align: "center" },
            { id: 'pathnow', header: '现有文件', dataIndex: 'PathNow', width: 180, sortable: true, align: "center" },
            { id: 'ispw', header: '是否加密', dataIndex: 'IsPw', width: 80, sortable: true, align: "center",
                renderer: function (v) {
                    if (v == false) {
                        return "未加密";
                    } else {
                        return "加密";
                    }
                }
            }

            ]);

    //创建下[每页行数]拉框
    var comboBox = new Ext.form.ComboBox({
        width: 50,
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        title: "每页行数",
        emptyText: pageSize,
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: ['myId', 'displayText'],
            data: [[10, 10], [20, 20], [30, 30], [50, 50], [100, 100]]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    }); comboBox.on("select", function (combo, record, index) {
        Ext.util.Cookies.set("pageSize", record.id);
        window.location.reload();
    });
    var grid = new Ext.grid.GridPanel({
        title: "文件列表",
        store: groupStore,
        border: true,
        margins: '5 0 5 0',
        region: 'center',
        view: new Ext.grid.GroupingView(),
        sm: sm,
        cm: cm,
        tbar: [{
            iconCls: 'icon-user_add-16',
            text: '上传',
            handler: function (btn) {
                viewport.items.get(2).expand();
                UserForm.getForm().reset();
                Ext.getCmp("saveBtn").setText("确认上传");
                UserForm.findByType('textfield')[1].focus(true, true);
            }
        }, {
            ref: '../removeBtn',
            iconCls: 'icon-user_delete-16',
            text: '删除',
            disabled: true,
            handler: function () {
                Ext.MessageBox.confirm("确认提示", "确认要删除所选行数据？", function (btn) {
                    if (btn == "yes") {
                        var s = grid.getSelectionModel().getSelections();
                        var delR = new Array();
                        var delRid = new Array();
                        for (var i = s.length - 1; i >= 0; i--) {
                            var r = s[i];
                            if (r.get('ID') != undefined) { delRid.push(r.get('ID')); delR.push(r); }
                        }
                        Ext.Ajax.request({
                            url: "SERVER/Files/FilesDel.aspx?modelid=" + modelid,
                            method: 'POST',
                            params: { id: delRid },
                            success: function (response) {
                                var json = Ext.util.JSON.decode(response.responseText);
                                if (json.success) {
                                    for (var i = 0; i < delR.length; i++) {
                                        if (json.ids.valueOf(delR[i].get('ID'))) { groupStore.remove(delR[i]) }
                                    }
                                    Ext.Msg.alert("提示", "已删除" + json.count + "行<br/>" + json.msg);
                                } else {
                                    Ext.Msg.alert("错误", json.msg);
                                }
                            }
                        });
                    }
                });
            }
        }, {
            ref: '../downBtn',
            iconCls: 'icon-user_add-16',
            text: '下载',
            disabled: true,
            handler: function () {
                var fd = new fileDown();
                var selectNode = grid.getSelectionModel().getSelections();
                if (selectNode[0].get("IsPw")) {
                    var pw = prompt("请输入密码", "**");
                    if (pw == selectNode[0].get("PW")) {
                        fd.fid = selectNode[0].get("ID");
                        fd.open();
                    } else {
                        Ext.Msg.alert("提示", "密码错误");
                    }
                    //                    Ext.Msg.prompt("密码", "请输入密码", function (btn, text) {
                    //                        if (btn == "ok") {
                    //                            if (text == selectNode[0].get("PW")) {
                    //                                fd.fid = selectNode[0].get("ID");
                    //                                fd.open();
                    //                            } else {
                    //                                Ext.Msg.alert("提示", "密码错误");
                    //                            }
                    //                        }
                    //                    });
                } else {
                    fd.fid = selectNode[0].get("ID");
                    fd.open();
                }
            }
        }],
        bbar: new Ext.PagingToolbar({
            store: groupStore,
            pageSize: pageSize,
            displayInfo: true,
            prependButtons: true,
            items: ['每页行数', comboBox, '-'],
            displayMsg: "本页显示第{0}条到第{1}条数据，共{2}条",
            emptyMsg: "暂无记录"
        })
    });
    var FoldersTree = new Ext.ux.ComboBoxTree({
        fieldLabel: "选文件夹",
        hiddenName: "ParentIDss",
        name: "ParentID",
        width: 143,
        emptyText: "选文件夹",
        editable: false,
        selectNodeModel: 'all',
        allowBlank: false,
        blankText: '文件名不能为空',
        tree: {
            xtype: 'treepanel',
            lines: true, rootVisible: false, border: false,
            loader: new Ext.tree.TreeLoader({ dataUrl: 'SERVER/Files/FoldersTree.aspx' }),
            root: new Ext.tree.AsyncTreeNode({ text: '选文件夹', id: "0", leaf: false })
        }
    });
    var radiogroup = new Ext.form.RadioGroup({
        width: 120,
        fieldLabel: "是否加密",
        items: [{
            boxLabel: '加密',
            inputValue: "true",
            name: "radiog",
            checked: true
        }, {
            boxLabel: '不加密',
            name: "radiog",
            inputValue: "false"
        }]
    });

    var UserForm = new Ext.form.FormPanel({
        region: 'east',
        split: true,
        width: 260,
        minSize: 260,
        maxSize: 300,
        collapsible: true,
        margins: '5 5 5 0',
        cmargins: '5',
        title: "编辑信息",
        bodyStyle: "padding:10px 5px;",
        labelAlign: "right",
        labelWidth: 60,
        buttonAlign: "center",
        defaultType: "textfield",
        border: true,
        items: [{ name: "ID", fieldLabel: "编号", disabled: true, value: 0, width: 140 },
                { name: "Name", fieldLabel: "文件名", width: 140, allowBlank: false, minLengthText: "长度不能小于6个字符",
                    maxLength: 50,
                    maxLengthText: "长度超过了20个字符", blankText: '文件名不能为空', regex: /[\u4e00-\u9fa5]/, regexText: "只能输入中文!"
                }, { name: "CreateTime", fieldLabel: "发布时间", xtype: 'datefield', format: "Y-m-d", value: new Date(), width: 143 },
                 radiogroup, //是否加密
                {name: "PW", fieldLabel: "输入密码", width: 140, inputType: "password" },
                 FoldersTree, //选文件夹
                 {name: "PathNow", fieldLabel: "现有文件", width: 140, disabled: true, value: "无" },
                 { name: "Type", fieldLabel: "文件类型", width: 140, disabled: true, value: "无" },
                 { name: "Size", fieldLabel: "文件大小", width: 140, disabled: true, value: "无" },
                { name: "Path", fieldLabel: "上传路径", inputType: "file", width: 150 }
               ],
        fileUpload: true,
        buttons: [{
            id: "saveBtn",
            text: "确定",
            handler: function () {
                if (UserForm.form.isValid()) {
                    var params = {
                        ID: UserForm.getForm().findField("ID").getValue(),
                        IsPw: UserForm.getForm().getValues()["radiog"],
                        ParentID: FoldersTree.getCtValue()
                    };
                    UserForm.getForm().submit({
                        method: "POST",
                        params: params,
                        url: "server/Files/FilesAdd.aspx?modelid=" + modelid,
                        success: function (form, action) {
                            if (action.result.success) {
                                Ext.Msg.alert("请求成功", action.result.msg, function () {
                                    groupStore.load({ params: { start: 0, limit: pageSize} });
                                });
                                UserForm.getForm().reset();
                            } else {
                                Ext.Msg.alert("错误", action.result.msg);
                            }
                        },
                        failure: function (form, action) { Ext.Msg.alert("请求失败", action.result.msg); }
                    });
                }
            }
        }, {
            text: "重置",
            handler: function () { UserForm.getForm().reset(); }
        }]
    });
    //创建页面布局
    var viewport = new Ext.Viewport({ layout: 'border', items: [DepmetTree, grid, UserForm] });
    viewport.items.get(2).collapse();
    //布局加载
    viewport.doLayout();
    //延时加载
    setTimeout(function () { Ext.get('loading').remove(); Ext.get('loading-mask').fadeOut({ remove: true }); }, 400);
    //有选择行启用删除按钮
    grid.getSelectionModel().on('selectionchange', function (sm) {
        grid.removeBtn.setDisabled(sm.getCount() < 1);
        grid.downBtn.setDisabled(sm.getCount() < 1 || sm.getCount() > 1);
    });
    grid.on('rowdblclick', function (g, index, e) {
        viewport.items.get(2).expand();
        Ext.getCmp("saveBtn").setText("确认更新");
        var r = g.getSelectionModel().getSelected();
        if (r != null) {
            UserForm.form.loadRecord(new UserInfo({ 'ID': r.get("ID"), 'radiog': (r.get("IsPw") ? r.get("IsPw") : "false"), 'Name': r.get("Name"), 'CreateTime': r.get("CreateTime"), 'Type': r.get("Type"), 'PW': r.get("PW"), 'IsPw': r.get("ParentID"), 'PathNow': r.get("PathNow"), 'Size': r.get("Size") }));
            FoldersTree.setCtValue(GetFoldersName(r.get("ParentID")), r.get("ParentID"));
        }
        UserForm.doLayout();
    });
});

var fileDown = function () {
    this.fid = 0;
    this.open = function () { window.open("server/Files/FilesDown.aspx?nodeid=" + this.fid); }
}